import { defineStore } from "pinia";
import { Icon } from "@iconify/vue";
import { sysUserApi } from "@/api";
import { views } from "@/views";
import { BasicLayout, BlankLayout } from "@/layouts";
import { isString } from "@/utils";
import { useTabStore } from "..";

export const useRouterStore = defineStore("routerStore", () => {
  const permsRoutes = ref<Sys.Route[]>([]);

  const menus = computed(() => {
    return route2Menu(permsRoutes.value);
  });

  const getPermsRoutes = async () => {
    const { code, data } = await sysUserApi.getRoute();
    if (code !== 1) permsRoutes.value = [];
    else permsRoutes.value = data;
    routeMapping(permsRoutes.value);

    // 初始化首页的tab
    useTabStore().initHomeTab(permsRoutes.value);
    console.log(permsRoutes.value);

    return permsRoutes.value;
  };

  return {
    permsRoutes,
    menus,
    getPermsRoutes,
  };
});

/**
 * 映射路由到对应的组件
 */
const routeMapping = (routes?: Sys.Route[]) => {
  if (!routes || !routes.length) return;

  let counter = 0;

  for (const route of routes) {
    if (route.meta?.type == 0) {
      route.component = markRaw(route.meta?.isRoot ? BasicLayout : BlankLayout);
      route.path = "/catalog" + counter++;
    } else if (isString(route.component)) {
      route.meta!.componentName = route.component as string;
      route.component = views[route.meta!.componentName];
    }
    routeMapping(route.children);
  }
};

/**
 * 路由转化为菜单
 */
const route2Menu = (routes?: Sys.Route[]): Sys.Menu[] | undefined => {
  if (!routes || !routes.length) return;

  return routes.map((route) => {
    return {
      label: route.meta!.title!,
      key: route.name,
      path: route.path,
      newTab: route.meta!.newTab!,
      icon: () => <Icon icon={route.meta!.icon!}></Icon>,
      children: route2Menu(route.children),
    };
  });
};
